<template>
  <div>
    <!-- 面包屑-->
    <el-breadcrumb separator-class='el-icon-arrow-right'>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>
    <el-card>
      <el-row>
        <el-col>
          <el-button type='primary' @click='addRole'>添加角色</el-button>
          <!--  添加角色面板-->
          <el-dialog
            title='添加角色'
            :visible.sync='addVisible'
            width='35%'>
            <el-form ref='addRoleFrom' :rules='editRoleRule' :model='addRoleFrom' label-width='100px'>
              <el-form-item label='角色名称' prop='roleName'>
                <el-input v-model='addRoleFrom.roleName'></el-input>
              </el-form-item>
              <el-form-item label='角色描述' prop='roleDesc'>
                <el-input v-model='addRoleFrom.roleDesc'></el-input>
              </el-form-item>
            </el-form>
            <span slot='footer' class='dialog-footer'>
    <el-button @click='addVisible = false'>取 消</el-button>
    <el-button type='primary' @click='addRoleForm'>确 定</el-button>
  </span>
          </el-dialog>
        </el-col>
      </el-row>
      <el-row>
        <el-divider></el-divider>
        <el-collapse v-model='collapseActive' @change='collapseName'>
          <el-collapse-item name='1'>
            <template slot='title'>
              <h3>{{ collapseTitle }}</h3>
            </template>
            <el-table :data='rolesList' border stripe>
              <el-table-column type='expand' label='@'>
                <template v-slot='scope'>
                  <el-row v-for='(item,i) in scope.row.children' :key='item.id'
                          :class='["border-bottom","center",i===0?"border-top":""]'>
                    <el-col :span='5'>
                      <el-tag type='primary' size='medium' closable
                              @close='delTagById(scope.row,item.id)'>{{ item.authName }}
                      </el-tag>
                      <i class='el-icon-caret-right'></i>
                    </el-col>
                    <el-col :span='19' :class='["border-left"]'>
                      <el-row v-for='(item2,i2) in item.children' :key='item2.id'
                              :class='[i2===0?"":"border-top","center"]'>
                        <el-col :span='6'>
                          <el-tag type='success' size='small' closable
                                  @close='delTagById(scope.row,item2.id)'>{{ item2.authName }}
                          </el-tag>
                          <i class='el-icon-caret-right'></i>
                        </el-col>
                        <el-col :span='18' :class='["border-left"]'>
                          <div v-if='item2.children.length!==0'>
                            <el-tag type='warning' v-for='item3 in item2.children' :key='item3.id' closable
                                    @close='delTagById(scope.row,item3.id)'>
                              {{ item3.authName }}
                            </el-tag>
                          </div>
                          <div v-else>
                            <span class='tag-empty'>暂无权限</span>
                          </div>
                        </el-col>
                      </el-row>
                    </el-col>
                  </el-row>
                </template>
              </el-table-column>
              <el-table-column type='index' label='#'></el-table-column>
              <el-table-column label='角色名称' prop='roleName'></el-table-column>
              <el-table-column label='角色描述' prop='roleDesc'></el-table-column>
              <el-table-column label='操作' width='300px'>
                <template v-slot='scope'>
                  <el-button type='primary' size='mini' icon='el-icon-edit' @click='editRole(scope.row)'>编辑</el-button>
                  <el-button type='danger' size='mini' icon='el-icon-delete' @click='delRole(scope.row.id)'>删除
                  </el-button>
                  <el-button type='warning' size='mini' icon='el-icon-s-tools' @click='powerBox(scope.row)'>分配权限
                  </el-button>
                  <!-- 编辑提交框-->
                  <el-dialog
                    title='编辑角色信息'
                    :visible.sync='roleVisible'
                    width='50%'>
                    <el-form ref='editRoleFrom' :rules='editRoleRule' :model='editRoleFrom' label-width='100px'>
                      <el-form-item label='角色名称' prop='roleName'>
                        <el-input v-model='editRoleFrom.roleName'></el-input>
                      </el-form-item>
                      <el-form-item label='角色描述' prop='roleDesc'>
                        <el-input v-model='editRoleFrom.roleDesc'></el-input>
                      </el-form-item>
                    </el-form>
                    <span slot='footer' class='dialog-footer'>
    <el-button @click='roleVisible = false'>取 消</el-button>
    <el-button type='primary' @click='updateRoleForm'>确 定</el-button>
  </span>
                  </el-dialog>
                  <!-- 分配权限提交框-->
                  <el-dialog
                    title='分配角色信息'
                    :visible.sync='powerVisible'
                    width='50%'
                    @close='clearPowerKeys'>
                    <el-tree :data='powerList'
                             :props='powerTreeProps'
                             show-checkbox
                             ref='tree'
                             node-key='id'
                             default-expand-all
                             :default-checked-keys='powerKeys'></el-tree>
                    <span slot='footer' class='dialog-footer'>
                      <el-button @click='powerVisible = false'>取 消</el-button>
                      <el-button type='primary' @click='updatePowerForm()'>确 定</el-button>
                    </span>
                  </el-dialog>
                </template>
              </el-table-column>
            </el-table>
          </el-collapse-item>
        </el-collapse>
      </el-row>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data() {
    return {
      collapseTitle: '点击收起',
      flag: true,
      collapseActive: '1',
      rolesList: [],
      roleVisible: false, // 编辑显示框
      powerVisible: false, // 分配角色显示框
      addVisible: false, // 添加角色显示框
      // 添加角色
      addRoleFrom: {
        roleName: '',
        roleDesc: ''
      },
      // 编辑修改角色
      editRoleFrom: {
        id: '',
        roleName: '',
        roleDesc: ''
      },
      // 编辑修改角色的规则
      editRoleRule: {
        roleName: [
          { required: true, message: '角色名称必填', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '角色说明必填', trigger: 'blur' }
        ]
      },
      // 所有权限列表
      powerList: [],
      // 定义展示的树形结构
      powerTreeProps: {
        label: 'authName',
        children: 'children'
      },
      // 当前角色ID
      powerId: '',
      // 保存所有三级权限的ID
      powerKeys: []
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$msg.error('获取角色列表失败')
      }
      this.rolesList = res.data
    },
    // 拉起添加角色框
    addRole() {
      this.addVisible = true
      this.$refs.addRoleFrom.resetFields()
    },
    // 添加角色
    async addRoleForm() {
      const { data: res } = await this.$http.post('roles', this.addRoleFrom)
      if (res.meta.status !== 201) {
        return this.$msg.error('添加角色失败')
      }
      this.$msg.success('添加角色成功')
      this.addVisible = false
      this.getRolesList()
    },
    // 点击收起改变collapse的title
    collapseName() {
      if (this.flag) {
        this.collapseTitle = '点击展开'
        this.flag = false
      } else {
        this.collapseTitle = '点击收起'
        this.flag = true
      }
    },
    // 拉起编辑用户权限
    editRole(data) {
      this.roleVisible = true
      this.editRoleFrom.id = data.id
      this.editRoleFrom.roleName = data.roleName
      this.editRoleFrom.roleDesc = data.roleDesc
    },
    // 发起请求修改用户权限
    async updateRoleForm() {
      const { data: res } = await this.$http.put('roles/' + this.editRoleFrom.id, {
        roleName: this.editRoleFrom.roleName,
        roleDesc: this.editRoleFrom.roleDesc
      })
      if (res.meta.status !== 200) {
        return this.$msg.error('修改角色信息失败')
      }
      this.$msg.success('修改角色信息成功')
      this.roleVisible = false
      this.getRolesList()
    },
    // 删除角色
    async delRole(id) {
      const res = await this.$confirm('是否删除该角色?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (res === 'confirm') {
        const { data: result } = await this.$http.delete('roles/' + id)
        if (result.meta.status !== 200) {
          this.$msg.error('删除角色失败')
        }
        this.$msg.success('删除角色成功')
        this.getRolesList()
      }
      if (res === 'cancel') {
        this.$msg.info('已取消')
      }
    },
    // 根据ID删除对应的权限标签
    async delTagById(roleId, tagId) {
      const res = await this.$confirm('你确定要删除该权限吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (res !== 'confirm') {
        return this.$msg.info('取消了删除')
      }
      const { data: result } = await this.$http.delete(`roles/${roleId.id}/rights/${tagId}`)
      if (result.meta.status !== 200) {
        return this.$msg.error('删除权限失败')
      }
      this.$msg.success('删除权限成功')
      roleId.children = result.data
    },
    // 点击分配按钮弹出提交框
    async powerBox(node) {
      this.powerId = node.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$msg.error('获取权限列表失败')
      }
      this.powerList = res.data
      this.checkedKeys(node, this.powerKeys)
      this.powerVisible = true
    },
    // 分配角色
    async updatePowerForm() {
      const key = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys())
      const { data: res } = await this.$http.post(`roles/${this.powerId}/rights`, { rids: String(key) })
      if (res.meta.status !== 200) {
        return this.$msg.error('角色授权失败')
      }
      this.$msg.success('角色授权成功')
      this.powerVisible = false
      await this.getRolesList()
    },
    // 递归获取三级权限的ID
    checkedKeys(node, arr) {
      // console.log(node)
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.checkedKeys(item, arr)
      })
    },
    // 点击关闭弹出框的时候，清除powerKeys的值
    clearPowerKeys() {
      this.powerKeys = []
    }
  }
}
</script>

<style lang='less' scoped>
.border-bottom {
  text-align: center;
  border-bottom: 1px solid #CCCCCC;
}

.el-tag {
  margin: 7px;
}

.border-top {
  border-top: 1px solid #CCCCCC;
}

.border-left {
  border-left: 1px solid #eeeeee;
}

.center {
  display: flex;
  align-items: center;
}

.tag-empty {
  color: #dcdcdc;
  font-size: 12px;
}
</style>
